package com.xxxx.yoyo.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xxxx.yoyo.bean.Goods;
import com.xxxx.yoyo.bean.Type;
import com.xxxx.yoyo.service.IGoodsService;
import com.xxxx.yoyo.service.ITypeService;
import com.xxxx.yoyo.service.impl.GoodsServiceImpl;
import com.xxxx.yoyo.service.impl.TypeServiceImpl;
import com.xxxx.yoyo.util.PageUtil;

/**
 * Servlet implementation class GoodsListServlet
 */
@WebServlet("/index/goods")
public class GoodsListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private ITypeService typeService = new TypeServiceImpl();
	private IGoodsService goodsService = new GoodsServiceImpl();
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//设置导航栏上的 [宠物分类] 处于选中状态
		request.setAttribute("flag", 2);
		
		//获取宠物分类列表
		List<Type> typeList = typeService.getTypeList();
		request.setAttribute("typeList", typeList);
		
		
		//获取前端页面传递过来的参数
		String typeIdStr = request.getParameter("typeid");//宠物分类的id
		String pageStr = request.getParameter("page");//当前第几页
		String sizeStr = request.getParameter("size");//每页条数
		//把字符串转换为整型
		int typeId = typeIdStr == null ? 1 : Integer.parseInt(typeIdStr);
		int page = pageStr == null ? 1 : Integer.parseInt(pageStr);
		int size = sizeStr == null ? 16 : Integer.parseInt(sizeStr);
		
		//根据宠物分类的id获取分类信息
		Type type = typeService.getTypeById(typeId);
		//把type存入request, 方便/index/goods.jsp页面使用
		request.setAttribute("type", type);
		
		//根据 [宠物分类,页码,每页条数] 获取宠物列表
		List<Goods> goodsList = goodsService.getGoodsListByTypeId(typeId, page, size);
		//把goodsList存入request, 方便/index/goods.jsp页面使用
		request.setAttribute("goodList", goodsList);
		
		//根据宠物分类的id获取宠物数量
		long count = goodsService.getGoodsCountByTypeId(typeId);
		
		//获取分页信息
		String pageInfo = PageUtil.getPageTool(request, count , page, size);
		//把pageInfo存入request, 方便/index/goods.jsp页面使用
		request.setAttribute("pageTool", pageInfo);
		
		//请求转发, 通过请求转发把页面跳转到/index/goods.jsp
		request.getRequestDispatcher("/index/goods.jsp").forward(request, response);
	}

}
